import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, Select, Checkbox, Table } from 'antd';
import { fetchSalaryReference } from '@/services/setting/salaryReference';
import { Pagination } from '@/components';
import { useDictionary } from '../../hooks';

const { Option } = Select;

const initPagination = {
    pageSize: 10,
    current: 1,
    total: 0
};

// 职位管理新增参考弹窗
const PostReferenceModal = ({ value, visible, onOk, onCancel, form, ...rest }) => {
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const [selectData, setSelectData] = useState(value?.map(item => ({ ...item, isChecked: true })) || []); // 选择的数据
    const [data, setData] = useState([]); // 表格数据源
    const [pagination, setPagination] = useState(initPagination); // 页码
    const [load, setLoad] = useState(false);

    const formatter = text => String(text ?? '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    const [sourceNameLoading, sourceNameList] = useDictionary({ code: 'salaryStandardSource' }); // 拉取数据名称字典数据

    // 获取列表数据
    const fetchData = async reset => {
        const values = form.getFieldsValue();
        const payload = {
            companyId: user.companyId,
            departmentId: user.departmentId,
            employeeCode: user.employeeCode,
            pageNo: reset ? 1 : pagination.current,
            pageSize: reset ? 10 : pagination.pageSize,
            searchName: values.searchName || '',
            sourceName: values.sourceName || ''
        };
        setLoad(true);
        form.setFieldsValue({ onlyChecked: false }); // 只看已选
        const response = await fetchSalaryReference(payload);
        if (response && response.code === 10000) {
            // 默认选中值
            const arr = response.data.rows?.map(item => {
                let isChecked = false;

                if (
                    selectData.findIndex(
                        subItem => subItem.salaryStandardName === item.salaryStandardName && subItem.id === item.id
                    ) > -1
                ) {
                    isChecked = true;
                }
                return { ...item, isChecked };
            });
            setData(arr);

            setPagination({
                ...pagination,
                total: response.data.total,
                pageSize: response.data.pageSize,
                current: response.data.pageNo
            });
        }
        setLoad(false);
    };

    const changeTable = p => {
        setPagination({
            ...pagination,
            ...p
        });
    };

    // 操作
    const handleActionChange = (e, record) => {
        const checkStatus = e.target.checked;
        const { salaryStandardName } = record;
        const tempArr = selectData;
        const index = tempArr.findIndex(item => item.salaryStandardName === salaryStandardName);
        if (checkStatus) {
            if (index > -1) {
                tempArr.splice(index, 1, { ...record, isChecked: true });
            } else {
                tempArr.push({ ...record, isChecked: true });
            }
        } else if (index > -1) {
            tempArr.splice(index, 1);
        }

        setSelectData([...tempArr]);

        const arr = data.map(item => {
            let isChecked = false;
            if (
                tempArr.findIndex(
                    subItem => subItem.salaryStandardName === item.salaryStandardName && subItem.id === item.id
                ) > -1
            ) {
                isChecked = true;
            }
            return { ...item, isChecked };
        });

        setData([...arr]);
    };

    // 表格列项
    const columns = [
        {
            title: '数据名称',
            dataIndex: 'salaryStandardName',
            width: 100
        },
        {
            title: '职位类别',
            dataIndex: 'postTypeName',
            width: 100
        },
        {
            title: '职位名称',
            dataIndex: 'postName',
            width: 150
        },
        {
            title: '职位代码',
            dataIndex: 'postCode',
            width: 120
        },
        {
            title: '一线25分位',
            dataIndex: 'firstLineTwoQuantile',
            render: formatter
        },
        {
            title: '一线50分位',
            dataIndex: 'firstLineFiveQuantile',
            render: formatter
        },
        {
            title: '一线75分位',
            dataIndex: 'firstLineSevenQuantile',
            render: formatter
        },
        {
            title: '一线90分位',
            dataIndex: 'firstLineNineQuantile',
            formatter
        },
        {
            title: '二线25分位',
            dataIndex: 'secondLineTwoQuantile',
            render: formatter
        },
        {
            title: '二线50分位',
            dataIndex: 'secondLineFiveQuantile',
            render: formatter
        },
        {
            title: '二线75分位',
            dataIndex: 'secondLineSevenQuantile',
            render: formatter
        },
        {
            title: '二线90分位',
            dataIndex: 'secondLineNineQuantile',
            formatter
        },
        {
            title: '操作',
            fixed: 'right',
            dataIndex: 'isChecked',
            width: 76,
            render: (text, record) => (
                <>
                    <Checkbox
                        defaultChecked={text}
                        key={`${record.id}${record.isChecked}`}
                        onChange={e => handleActionChange(e, record)}
                    />
                </>
            )
        }
    ];

    // 搜索
    const handleSearch = e => {
        e.preventDefault();
        fetchData(1);
    };

    useEffect(() => {
        fetchData();
    }, [pagination.pageSize, pagination.current]);

    const { getFieldDecorator } = form;
    return (
        <Modal
            centered
            title="薪资参考"
            visible={visible}
            width={940}
            afterClose={() => {
                form.resetFields();
            }}
            onOk={() => {
                if (onOk) {
                    onOk(selectData);
                }
            }}
            onCancel={onCancel}
            bodyStyle={{ padding: '20px 24px 8px' }}
            {...rest}
        >
            <Form layout="inline" onSubmit={handleSearch} style={{ marginBottom: 16 }}>
                <Form.Item label="关键字">
                    {getFieldDecorator('searchName')(
                        <Input style={{ width: '100%' }} placeholder="请输入关键词" allowClear />
                    )}
                </Form.Item>
                <Form.Item label="数据名称">
                    {getFieldDecorator('sourceName')(
                        <Select
                            style={{ width: 130 }}
                            placeholder="请选择数据名称"
                            allowClear
                            loading={sourceNameLoading}
                        >
                            {sourceNameList?.map(item => (
                                <Option value={item.dictValue} key={item.dictValue}>
                                    {item.dictName}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('onlyChecked', { valuePropName: 'checked' })(<Checkbox>只看已选</Checkbox>)}
                </Form.Item>
            </Form>
            <Table
                loading={load}
                dataSource={form.getFieldValue('onlyChecked') === true ? selectData : data}
                columns={columns}
                scroll={{
                    x: 1366,
                    y: 360
                }}
                rowKey="id"
                pagination={false}
            />

            <Pagination loading={load} onChange={changeTable} {...pagination} />
        </Modal>
    );
};

export default Form.create({ name: 'PostReferenceModal' })(PostReferenceModal);
